package com.jingdianjichi.interview.server.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.Objects;
import com.alibaba.nacos.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jingdianjichi.interview.api.enums.IsDeletedFlagEnum;
import com.jingdianjichi.interview.api.req.GetShareCommentReq;
import com.jingdianjichi.interview.api.req.RemoveShareCommentReq;
import com.jingdianjichi.interview.api.req.SaveShareCommentReplyReq;
import com.jingdianjichi.interview.api.vo.ShareCommentReplyVO;
import com.jingdianjichi.interview.server.entity.po.ShareCommentReply;
import com.jingdianjichi.interview.server.entity.po.ShareMoment;
import com.jingdianjichi.interview.server.mapper.ShareCommentReplyMapper;
import com.jingdianjichi.interview.server.mapper.ShareMomentMapper;
import com.jingdianjichi.interview.server.rpc.UserRpc;
import com.jingdianjichi.interview.server.rpc.entity.UserInfo;
import com.jingdianjichi.interview.server.service.ShareCommentReplyService;
import com.jingdianjichi.interview.server.utils.LoginUtil;
import com.jingdianjichi.interview.server.utils.TreeUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName:ShareCommentReplyServiceImpl
 * Package:com.jingdianjichi.circle.server.service.Impl
 * Description:
 *
 * @Author fst
 * @Create 2025/2/17 23:10
 * @Version 1.0
 */
@Service
public class ShareCommentReplyServiceImpl extends ServiceImpl<ShareCommentReplyMapper, ShareCommentReply>
        implements ShareCommentReplyService {

    @Resource
    private ShareMomentMapper shareMomentMapper;


    @Resource
    private UserRpc userRpc;

    @Override
    public Boolean saveComment(SaveShareCommentReplyReq req) {
        ShareMoment moment = shareMomentMapper.selectById(req.getMomentId());

        ShareCommentReply comment=new ShareCommentReply();

        comment.setMomentId(Long.valueOf(req.getMomentId()));
        comment.setReplyType(req.getReplyType());

        String loginId= LoginUtil.getLoginId();

        if(req.getReplyType()==1)
        {
            comment.setParentId(-1L);
            comment.setToId(req.getTargetId());
            comment.setToUser(loginId);
            boolean isAuthor=Objects.nonNull(moment.getCreatedBy())&&loginId.equals(moment.getCreatedBy());
            comment.setToUserAuthor(isAuthor?1:0);
        }
        else if(req.getReplyType()==2)
        {
            comment.setParentId(req.getTargetId());
            comment.setReplyId(req.getTargetId());
            comment.setReplyUser(loginId);
            comment.setReplayAuthor(Objects.nonNull(moment.getCreatedBy())&&loginId.equals(moment.getCreatedBy())?1:0);
        }

        comment.setContent(req.getContent());

        if(!CollectionUtils.isEmpty(req.getPicUrlList()))
        {
            comment.setPicUrls(JSON.toJSONString(req.getPicUrlList()));
        }

        comment.setCreatedBy(loginId);
        comment.setCreatedTime(new Date());
        comment.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        shareMomentMapper.incrReplyCount(moment.getId(),1);

        return super.save(comment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeComment(RemoveShareCommentReq req) {

        ShareCommentReply comment = getById(req.getId());
        LambdaQueryWrapper<ShareCommentReply> query = Wrappers.<ShareCommentReply>lambdaQuery()
                .eq(ShareCommentReply::getMomentId, comment.getMomentId())
                .eq(ShareCommentReply::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode()).select(ShareCommentReply::getId,
                        ShareCommentReply::getMomentId,
                        ShareCommentReply::getReplyType,
                        ShareCommentReply::getContent,
                        ShareCommentReply::getPicUrls,
                        ShareCommentReply::getCreatedBy,
                        ShareCommentReply::getToUser,
                        ShareCommentReply::getParentId);

        List<ShareCommentReply> list=list(query);

        List<ShareCommentReply> replyList =new ArrayList<>();

        List<ShareCommentReply> tree= TreeUtils.buildTree(list);

        for(ShareCommentReply reply:tree)
        {
           TreeUtils.findAll(replyList,reply,reply.getId());
        }

        Set<Long> ids =replyList.stream().map(ShareCommentReply::getId).collect(Collectors.toSet());

        LambdaUpdateWrapper<ShareCommentReply> update= Wrappers.<ShareCommentReply>lambdaUpdate()
                .eq(ShareCommentReply::getMomentId,comment.getMomentId())
                .in(ShareCommentReply::getId,ids);

        ShareCommentReply updateEntity=new ShareCommentReply();

        updateEntity.setIsDeleted(IsDeletedFlagEnum.DELETED.getCode());

        int count = getBaseMapper().update(updateEntity,update);

        shareMomentMapper.incrReplyCount(comment.getMomentId(),-count);

        return true;

    }

    @Override
    public List<ShareCommentReplyVO> listComment(GetShareCommentReq req) {

        LambdaQueryWrapper<ShareCommentReply> query = Wrappers.<ShareCommentReply>lambdaQuery()
                .eq(ShareCommentReply::getMomentId, req.getId())
                .eq(ShareCommentReply::getIsDeleted, IsDeletedFlagEnum.UN_DELETED.getCode())
                .select(ShareCommentReply::getId,
                        ShareCommentReply::getMomentId,
                        ShareCommentReply::getReplyType,
                        ShareCommentReply::getContent,
                        ShareCommentReply::getPicUrls,
                        ShareCommentReply::getCreatedBy,
                        ShareCommentReply::getToUser,
                        ShareCommentReply::getCreatedTime,
                        ShareCommentReply::getParentId);
        List<ShareCommentReply> list = list(query);

        List<String> userNameList=list.stream().map(ShareCommentReply::getCreatedBy).distinct().collect(Collectors.toList());

        Map<String,UserInfo> userInfoMap =userRpc.batchGetUserInfo(userNameList);

        List<ShareCommentReplyVO> voList = list.stream().map(item ->
        {
            UserInfo defaultUser = new UserInfo();
            ShareCommentReplyVO vo = new ShareCommentReplyVO();
            vo.setId(item.getId());
            vo.setMomentId(item.getMomentId());
            vo.setReplyType(item.getReplyType());
            vo.setContent(item.getContent());
            if (Objects.nonNull(item.getPicUrls())) {
                vo.setPicUrlList(JSONArray.parseArray(item.getPicUrls(), String.class));
            }
            if (item.getReplyType() == 2) {
                vo.setFromId(item.getCreatedBy());
                vo.setToId(item.getToUser());
            }
            vo.setParentId(item.getParentId());
            UserInfo user = userInfoMap.getOrDefault(item.getCreatedBy(), defaultUser);
            vo.setUserName(user.getNickName());
            vo.setAvatar(user.getAvatar());
            vo.setCreatedTime(item.getCreatedTime().getTime());
            if (StringUtils.isNotBlank(item.getToUser())) {
                UserInfo toUser = userInfoMap.getOrDefault(item.getToUser(), defaultUser);
                vo.setToAvatar(toUser.getAvatar());
                vo.setToName(toUser.getNickName());
            }

            return vo;
        }).collect(Collectors.toList());
        return TreeUtils.buildTree(voList);





    }
}
